<template>
    <div>
        <basic-container>
            <avue-crud
                    :data="list"
                    :option="option"
                    ref="crud"
                    v-model="form"
                    :permission="permission"
                    @on-load="getList"
                    :table-loading="listLoading"
                    :page="page"
                    @search-change="handleFilter"
                    @refresh-change="handleRefreshChange"
                    @row-save="save"
                    @row-update="update"
                    @row-del="deletes"
                    :before-open="beforeOpen">
                <template slot="roles"
                          slot-scope="scope">
              <span v-for="(role,index) in scope.row.roles"
                    :key="index">
                <el-tag>{{role.name}} </el-tag>&nbsp;&nbsp;
              </span>
                </template>
                <template slot="rolesForm"
                          slot-scope="scope">
                    <avue-select v-model="form.roles"
                                      multiple
                                      placeholder="请选择角色"
                                      :dic="rolesOptions"
                                      :props="defaultProps"></avue-select>
                </template>
                <template slot="deptIdForm"
                          slot-scope="scope">
                    <avue-input v-model="form.deptId"
                                     type="tree"
                                     placeholder="请选择所属部门"
                                     :dic="treeDeptData"
                                     :props="defaultProps"></avue-input>
                </template>
            </avue-crud>
        </basic-container>
    </div>
</template>

<script>
    import {listPage,saveUser,updateUser,deleteUser} from "@/api/user";
    import {deptTree} from "@/api/dept";
    import {roleList} from "@/api/role";
    import {tableOption} from '@/const/user';
    import {mapGetters} from "vuex";

    export default {
        data() {
            return {
                page: {
                    total: 0, // 总页数
                    currentPage: 1, // 当前页数
                    pageSize: 10, // 每页显示多少条,
                    isAsc: false//是否倒序
                },
                listLoading: false,
                list: [],
                option: tableOption,
                permission:{
                    delBtn: false
                },
                roles: [],
                form: {},
                role: [],
                rolesOptions: [],
                treeDeptData:[],
                defaultProps: {
                    label: "name",
                    value: 'id'
                }
            }
        },
        created() {
            this.permission = {
                viewBtn: this.permissions['sys_user_view']?true:false,
                addBtn: this.permissions['sys_user_add']?true:false,
                delBtn: this.permissions['sys_user_del']?true:false,
                editBtn: this.permissions['sys_user_edit']?true:false,
                searchBtn: true
            }
        },
        computed: {
            ...mapGetters(["permissions"])
        },
        watch: {
            role() {
                this.form.roles = this.role
            }
        },
        methods: {
            //获取分页数据
            getList(page, params) {
                this.listLoading = true;
                listPage(Object.assign({
                    current: page.currentPage,
                    size: page.pageSize
                }, params)).then(response => {
                    this.list = response.data.data.records
                    this.page.total = response.data.data.total
                    this.listLoading = false;
                })
            },
            beforeOpen(show, type) {
                window.boxType = type;
                roleList().then(response => {
                    this.rolesOptions = response.data.data
                })
                deptTree().then(response => {
                    this.treeDeptData = response.data.data
                })
                if (['edit', 'views'].includes(type)) {
                    this.role = [];
                    for (let i = 0; i < this.form.roles.length; i++) {
                        this.role[i] = this.form.roles[i].id;
                    }
                } else if (type === 'add') {
                    this.role = [];
                }
                show();
            },
            save(row, done,loading) {
                saveUser(this.form).then(() => {
                    this.getList(this.page);
                    done();
                    this.$notify({
                        title: "成功",
                        message: "创建成功",
                        type: "success",
                        duration: 2000
                    });
                }).catch(() => {
                    loading();
                });
            },
            update(row, done,loading) {
                updateUser(this.form).then(() => {
                    this.getList(this.page);
                    done();
                    this.$notify({
                        title: "成功",
                        message: "更新成功",
                        type: "success",
                        duration: 2000
                    });
                }).catch(() => {
                    loading();
                });
            },
            deletes(row,index){
                this.$confirm(
                    "此操作将永久删除该用户(" + row.userName + "), 是否继续?",
                    "提示",
                    {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning"
                    }
                ).then(() =>{
                    deleteUser(row.userId).then(() =>{
                        this.list.splice(index, 1);
                        this.$notify({
                            title: "成功",
                            message: "删除成功",
                            type: "success",
                            duration: 2000
                        });
                        this.getList(this.page);
                    }) .cache(() => {
                        this.$notify({
                            title: "失败",
                            message: "删除失败",
                            type: "error",
                            duration: 2000
                        });
                    });
                })
            },
            handleFilter(param) {
                this.page.page = 1;
                this.getList(this.page, param);
            },
            handleRefreshChange() {
                this.getList(this.page)
            }
        }
    }
</script>
